﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Security.Cryptography;
using MMS.DAL;
using MMS.Model;

namespace MMS.BLL
{
    public class AdminService
    {
        /// <summary>
        /// 实例化SqlServerDBHelper
        /// </summary>
        DBHelper db = new SqlServerDBHelper();

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public string EncryptWithMD5(string source)
        {
            byte[] sor = Encoding.UTF8.GetBytes(source);
            MD5 md5 = MD5.Create();
            byte[] result = md5.ComputeHash(sor);
            StringBuilder strbul = new StringBuilder(40);
            for (int i = 0; i < result.Length; i++)
            {
                strbul.Append(result[i].ToString("x2"));//加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位

            }
            return strbul.ToString().ToLower();
        }
        /// <summary>
        /// 使用用户名和密码登录并获取用户信息对象
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        public AdminInfo Login(string name, string pass)
        {
            string sql = string.Format(@"select * from AdminInfo 
where AdminName='{0}' and AdminPass='{1}'", name, EncryptWithMD5(pass));
            Console.WriteLine(sql);
            ///数据库查询操作：使读取器前进到结果集中的下一条记录
            DbDataReader dr = db.ExecuteReader(sql);
            ///申明一个AdminInfo 类型的变量 赋值为NULL
            AdminInfo admin = null;
            if (dr.Read())//判断是否读取到数据
            {
                admin = new AdminInfo();
                admin.AdminId = Convert.ToInt32(dr["AdminId"]);
                admin.AdminName = dr["AdminName"].ToString();
                admin.AdminPass = dr["AdminPass"].ToString();
                admin.AdminRole = Convert.ToInt32(dr["AdminRole"]);
                admin.AdminStatus = Convert.ToInt32(dr["AdminStatus"]);
            }
            ///关闭DbDataReader 
            dr.Close();
            ///关闭数据库连接
            db.Close();
            ///返回admin 方便界面层直接接受 
            return admin;
        }
    }
}
